package com.movieknight;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class SQLFriendsDataSource {
	// Database fields
	private SQLiteDatabase database;
	private MySQLiteHelper dbHelper;
	private String[] allColumns = { MySQLiteHelper.COLUMN_ID,
			MySQLiteHelper.COLUMN_FRIEND };

	public SQLFriendsDataSource(Context context) {
		dbHelper = new MySQLiteHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public Friend createFriend(String friend) {
		ContentValues values = new ContentValues();
		values.put(MySQLiteHelper.COLUMN_FRIEND, friend);
		long insertId = database.insert(MySQLiteHelper.TABLE_FRIENDS, null,
				values);
		Cursor cursor = database.query(MySQLiteHelper.TABLE_FRIENDS,
				allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
				null, null, null);
		cursor.moveToFirst();
		Friend newFriend = cursorToFriend(cursor);
		cursor.close();
		return newFriend;
	}

	public void deleteFriend(long id) {
		database.delete(MySQLiteHelper.TABLE_FRIENDS, MySQLiteHelper.COLUMN_ID + " = " + id, null);
	}

	public List<Friend> getAllFriends() {
		List<Friend> friends = new ArrayList<Friend>();

		Cursor cursor = database.query(MySQLiteHelper.TABLE_FRIENDS,
				allColumns, null, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Friend friend = cursorToFriend(cursor);
			friends.add(friend);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return friends;
	}

	private Friend cursorToFriend(Cursor cursor) {
		Friend friend = new Friend();
		friend.setId(cursor.getLong(0));
		friend.setName(cursor.getString(1));
		return friend;
	}
}
